package com.project.controller.web;

import com.alibaba.fastjson.JSONObject;
import com.project.common.utils.MyPageHelper;
import com.project.entity.*;
import com.project.myBeans.R;
import com.project.myBeans.StudentInfoDetail;
import com.project.service.*;
import com.project.service.base.BaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: TateBrown
 * @date: 2018/5/26 19:53
 * @param:
 * @return:
 */
@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping(value = "/student")
@Api(description = "学生信息接口",value = "student")
public class StudentController extends BaseService {
    @Autowired
    UserService userService;
    @Autowired
    StudentInfoService studentInfoService;
    @Autowired
    private TeacherInfoService teacherInfoService;
    @Autowired
    private ClassService classService;
    @Autowired
    private SchoolManagerInfoService schoolManagerInfoService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private MajorService majorService;
    @Autowired
    private SchoolService schoolService;


    public static final int STUDENTSTATE_NO = 1;//未实习

    public static final int STUDENTSTATE_APPLY = 2;//实习申请中（当前未在实习）

    public static final int STUDENTSTATE_ING = 3;//正在实习中

    public static final int STUDENTSTATE_CHANGE = 4;//实习变更申请中（当前仍在实习）

    public static final int STUDENTSTATE_GRADUATE = -1;//已经毕业

    /**
     * TateBrown 2018年5月27日
     *
     * @param studentInfo
     * @return
     */
    @ApiOperation("根据userid修改学生表信息")
    @PostMapping("/modify")
    public R ModifyOneByUserId(@RequestBody StudentInfo studentInfo){
        try{
            if(processSuccessDeleteUpdate(studentInfoService.modifyByUserIdSelective(studentInfo))){
                return R.ok("修改成功");
            }else{
                return R.error("修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param studentInfo
     * @return
     */
    @ApiOperation("根据id修改学生表信息")
    @PostMapping("/modifyOneById")
    public R modifyOneById(@RequestBody StudentInfo studentInfo){
        try{
            if(processSuccessDeleteUpdate(studentInfoService.modifyOneById(studentInfo))){
                return R.ok("修改成功");
            }else{
                return R.error("修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param studentInfoDetail
     * @return
     */
    @ApiOperation("修改学生详细信息（影响用户表+学生信息表）")
    @PostMapping("/modifyOrAddDetail")
    public R modifyOrAddDetail(@RequestBody StudentInfoDetail studentInfoDetail){
        try{
            if(studentInfoDetail.getUser()!=null)
                userService.updateUser(studentInfoDetail.getUser());
            if(studentInfoDetail.getStudentInfo()!=null)
                if(studentInfoService.findOneByUserId(studentInfoDetail.getStudentInfo().getUserid())!=null){
                studentInfoService.modifyByUserIdSelective(studentInfoDetail.getStudentInfo());
                }else{
                studentInfoService.add(studentInfoDetail.getStudentInfo());
                }
                return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param studentInfoDetail
     * @return
     */
    @ApiOperation("添加学生详细信息")
    @PostMapping("/addDetailOne")
    public R addDetailOne(@RequestBody StudentInfoDetail studentInfoDetail){
        try{
            studentInfoService.addDetailOne(studentInfoDetail);
            return R.ok("添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param studentInfoDetail
     * @return
     */
    @ApiOperation("修改学生详细信息")
    @PostMapping("/modifyDetailOne")
    public R modifyDetailOne(@RequestBody StudentInfoDetail studentInfoDetail){
        try{
            studentInfoService.modifyDetailOne(studentInfoDetail);
            return R.ok("修改成功");
        }catch (Exception e){
            return R.error();
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param userId
     * @return
     */
    @ApiOperation("查询学生个人详细信息")
    @GetMapping("/findDetail/{userId}")
    public R findDetailOneByUserId(@PathVariable("userId")Integer userId){
         try{
             return R.ok("查找成功").put("data",studentInfoService.findDetailByUserId(userId));
         }catch (Exception e){
             e.printStackTrace();
             return R.error("程序异常");
         }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param user
     * @return
     */
    @ApiOperation("根据校内指导老师userid批量查找学生详细信息 + 分页 + 条件")
    @PostMapping("/findDetailBatchByInternAdvisor")
    public R findDetailBatchByInternAdvisor(@RequestBody User user){
        try{
            StudentInfo studentInfo = new StudentInfo();
            //先找出通过老师userid找到教师信息表id
            if (user.getId() != null) {
                TeacherInfo teacherInfo = teacherInfoService.findOneByUserId(user.getId());
                studentInfo.setPageSize(user.getPageSize());
                studentInfo.setPageIndex(user.getPageIndex() - 1);
                if (teacherInfo != null) {
                    studentInfo.setInternadvisor(teacherInfo.getId());
                    //再通过教师信息表id查符合条件学生
                    List<StudentInfo> studentInfoList = studentInfoService.findBatchByCondition(studentInfo);
                    //找出每个学生的详细信息
                    List<StudentInfoDetail> studentInfoDetails = new ArrayList<>();
                    for (StudentInfo studentInfo1 : studentInfoList) {
                        studentInfoDetails.add(studentInfoService.findDetailById(studentInfo1.getId()));
                    }

                    return R.ok("获取成功").put("data",studentInfoDetails).put("total", MyPageHelper.getTotal(studentInfoDetails));
                } else {
                    return R.error("缺少教师信息");
                }
            } else {
                return R.error("缺少老师id");
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.error();
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param schoolManagerInfo
     * @return
     */
    @ApiOperation("根据学院id批量查找学生详细信息 + 分页 + 条件")
    @PostMapping("/findDetailBatchBySchoolId")
    public R findDetailBatchBySchoolId(@RequestBody SchoolManagerInfo schoolManagerInfo){
        try{
            //获取学院管理员的学院id
            SchoolManagerInfo schoolManagerInfo1 = schoolManagerInfoService.findByUserId(schoolManagerInfo.getUserid());
            Integer schoolId = schoolManagerInfo1.getSchoolid();
            StudentInfo studentInfo = new StudentInfo();
            studentInfo.setPageSize(schoolManagerInfo.getPageSize());
            studentInfo.setPageIndex(schoolManagerInfo.getPageIndex() - 1);
            studentInfo.setSchoolid(schoolId);
            //再通过学生信息信息表id查符合条件学生
            List<StudentInfo> studentInfoList = studentInfoService.findBatchByCondition(studentInfo);
            //找出每个学生的详细信息
            List<JSONObject> jsonObjectList = new ArrayList<>();
            for (StudentInfo studentInfo1 : studentInfoList) {
                JSONObject jsonObject = new JSONObject();
                //学生表信息
                jsonObject.put("studentInfo", studentInfo1);
                //用户表信息
                jsonObject.put("user", userService.findOneByUserID(studentInfo1.getUserid()));
                //系
                if (studentInfo1.getDepartmentid() != null)
                    jsonObject.put("department", departmentService.findOne(studentInfo1.getDepartmentid()));
                //专业
                if (studentInfo1.getMajorid() != null)
                    jsonObject.put("major", majorService.findOne(studentInfo1.getMajorid()));
                //班级
                if (studentInfo1.getClassid() != null)
                    jsonObject.put("class", classService.findOne(studentInfo1.getClassid()));
//                studentInfoDetails.add(studentInfoService.findDetailById(studentInfo1.getId()));
                jsonObjectList.add(jsonObject);
            }
            return R.ok("获取成功").put("data",jsonObjectList).put("total",MyPageHelper.getTotal(jsonObjectList));
        }catch (Exception e){
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param internAdvisorUserId
     * @return
     */
    @ApiOperation("根据internAdvisorUserId获取该老师指导下的学生们的用户表信息（仅解密姓名)")
    @GetMapping("/findBatchByInternAdvisorUserId/{internAdvisorUserId}")
    public R findBatchByInternAdvisorUserId(@PathVariable("internAdvisorUserId") Integer internAdvisorUserId){
        try{
         return R.ok("查找成功").put("data",studentService.findBatchByInternAdvisorUserId(internAdvisorUserId));
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param studentInfoDetail
     * @return
     */
    @ApiOperation("筛选学校、自我介绍为条件查找学生信息")
    @PostMapping("/findBatchByCondition")
    public R findBatchByCondition(@RequestBody StudentInfoDetail studentInfoDetail){
        List<School> schoolList = null;
        StudentInfo studentInfo;
        try {
            User user = studentInfoDetail.getUser();
            //查出学生对应学院idList
            if (user != null)
                if (user.getUniversityid() != null){
                    schoolList = schoolService.findBatchByUniversityId(user.getUniversityid());
                    if (schoolList.size() == 0) {
                        return R.error("无学生信息");
                    }
                }

            //设置学生信息表信息
            if (studentInfoDetail.getStudentInfo() == null){
                studentInfo = new StudentInfo();
                studentInfo.setPageIndex(studentInfoDetail.getPageIndex() - 1);
                studentInfo.setPageSize(studentInfoDetail.getPageSize());
            }
            else {
                studentInfo = studentInfoDetail.getStudentInfo();
                studentInfo.setPageIndex(studentInfoDetail.getPageIndex() - 1);
                studentInfo.setPageSize(studentInfoDetail.getPageSize());
            }
            List<JSONObject> jsonObjectList1 = studentInfoService.findBatchByConditionWithSchoolList(schoolList, studentInfo);
            MyPageHelper.setPageParam(studentInfoDetail);
            List<JSONObject> jsonObjectList = studentInfoService.findBatchByConditionWithSchoolList(schoolList, studentInfo);

            return R.ok("查找成功").put("data",jsonObjectList).put("total",MyPageHelper.getTotal(jsonObjectList1));
            //再通过学生信息信息表id查符合条件学生
//            List<StudentInfo> studentInfoList = studentInfoService.findBatchByCondition(studentInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * TateBrown 2018年5月25日
     *
     * @param studentInfoDetail
     * @return
     */
    @ApiOperation("创建学生账户")
    @PostMapping("/addStudentAccount")
    public R addStudentAccount(@RequestBody StudentInfoDetail studentInfoDetail){
        try {
            if (studentService.addDetailOne(studentInfoDetail.getUser(), studentInfoDetail.getStudentInfo())){
                return R.ok("创建成功");
            }
            else {
               return R.error("用户名已经存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * TateBrown 2018年5月26日
     *
     * @param userId
     * @return
     */
    @ApiOperation("删除学生及其相关所有信息")
    @GetMapping("/removeOneByUserId/{userId}")
    public R removeOneChainById(@PathVariable("userId")Integer userId){
        try {
            //找出学生对应学生表信息
            StudentInfo studentInfo = studentInfoService.findOneByUserId(userId);
            List<StudentInfo> studentInfoList = new ArrayList<>();
            studentInfoList.add(studentInfo);

            studentService.removeBatchChain(studentInfoList);
            return R.ok("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("程序异常");
        }
    }
}
